package com.hs.shirodemo01.service.impl;

import com.hs.shirodemo01.pojo.TbPermission;
import com.hs.shirodemo01.pojo.TreeSelect;
import com.hs.shirodemo01.service.MenuService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName MenuServiceImpl
 * @Description
 */

@Service
public class MenuServiceImpl implements MenuService {


    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t 子节点
     */
    private void recursionFn(List<TbPermission> list, TbPermission t)
    {
        // 得到子节点列表
        List<TbPermission> childList = getChildList(list, t);
        t.setChildren(childList);
        for (TbPermission tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    private boolean hasChild(List<TbPermission> list, TbPermission t)
    {
        return getChildList(list, t).size() > 0;
    }


    /**
     * 得到子节点列表
     */
    private List<TbPermission> getChildList(List<TbPermission> list, TbPermission t)
    {
        List<TbPermission> tlist = new ArrayList<>();
        Iterator<TbPermission> it = list.iterator();
        while (it.hasNext())
        {
            TbPermission n = (TbPermission) it.next();
            if (n.getParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    @Override
    public List<TbPermission> buildMenuTree(List<TbPermission> menus) {
        List<TbPermission> returnList = new ArrayList<>();
        List<Integer> tempList = menus.stream().map(TbPermission::getId).collect(Collectors.toList());
        for (Iterator<TbPermission> iterator = menus.iterator(); iterator.hasNext();)
        {
            TbPermission menu = (TbPermission) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId()))
            {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
    }

    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<TbPermission> menus) {
        List<TbPermission> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }
}
